import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入 store
import store from '@/store'

Vue.use(VueRouter)

// 路由规则（添加需要认证的 requiresAuth 信息）
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: 'login' */'@/views/login/index')
  },
  {
    path: '/list',
    name: 'list',
    component: () => import(/* webpackChunkName: 'login' */'@/views/mother/list')
  },
  {
    path: '/',
    component: () => import(/* webpackChunkName: 'layout' */'@/views/layout/index'),
    // 直接给某个路由设置，这时内部的子路由都需要认证（包含当前路由）
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'home',
        meta: { title: '首页' },
        component: () => import(/* webpackChunkName: 'home' */'@/views/home/index')
      },
      {
        path: 'task',
        name: 'task',
        meta: { title: '评价页面' },
        component: () => import(/* webpackChunkName: 'menu' */'@/views/task/index')
      },
      // 添加菜单路由组件
      {
        path: 'task/:id/create',
        name: 'task-create',
        meta: { title: 'GPT数据' },
        component: () => import(/* webpackChunkName: 'menu-create' */'@/views/task/create')
      },
      {
        path: 'task/:id/:gpt/config',
        name: 'task-config',
        meta: { title: 'GPT评价' },
        component: () => import(/* webpackChunkName: 'menu-create' */'@/views/task/config')
      },
      {
        path: 'task/:id/record',
        name: 'task-record',
        component: () => import(/* webpackChunkName: 'menu-create' */'@/views/task/record')
      },
      {
        path: 'mother',
        name: 'mother',
        meta: { title: '华西附二院' },
        component: () => import(/* webpackChunkName: 'menu' */'@/views/mother/index')
      },
      // 添加菜单路由组件
      {
        path: 'mother/create',
        name: 'mother-create',
        component: () => import(/* webpackChunkName: 'menu-create' */'@/views/mother/create')
      },
      {
        path: 'mother/:id/config',
        name: 'mother-config',
        component: () => import(/* webpackChunkName: 'menu-create' */'@/views/mother/config')
      },
      {
        path: 'mother/:id/record',
        name: 'mother-record',
        component: () => import(/* webpackChunkName: 'menu-create' */'@/views/mother/record')
      }
    ]
  },
  {
    path: '*',
    name: 'error-page',
    component: () => import(/* webpackChunkName: 'error-page' */'@/views/error-page/index')
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  console.log(to)
  // 验证 to 路由是否需要进行身份认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 验证 Vuex 的 store 中的登录用户信息是否存储
    if (!store.state.user) {
      // 未登录，跳转到登录页
      return next({
        name: 'login',
        query: {
          // 将本次路由的 fullPath 传递给 login 页面
          redirect: to.fullPath
        }
      })
    }
    // 已经登录，允许通过
    next()
  } else {
    next()
  }
})

export default router
